import Vue from 'vue';
import router from './router';
import store from './store';

import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { setDocumentTitle, domTitle } from '@/utils/domUtil';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { showErrors, showError, showSuccess } from '@/utils/showMsg';


NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ['login','Register','upForgetPassword']; // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start(); // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`));
  if (Vue.ls.get(ACCESS_TOKEN)) {
    store.dispatch('GetInfo').then(response => {
      if(response.data.errorCode === 0){
        const roles = response.data.result
        console.log('roles',roles);
        if(typeof roles != "undefined") {
          let equipmentList = {}
          let homeBtn = []
          let controlCenter = []
          roles.permissionList = []
          roles.permission.forEach(item => {
            roles.permissionList.push(item.name)
            if (item.children) {
              item.children.forEach(childrenItem=>{
                // 判断是否有设备列表权限
                if (childrenItem.name == 'equipment_list') {
                  equipmentList = childrenItem
                }
                //控制中心 定时任务权限和地图按钮权限
                if (childrenItem.name == 'timing_add' || childrenItem.name == 'control_briefing' || childrenItem.name == 'data_historyForm' || childrenItem.name == 'equipment_list' || childrenItem.name == 'YieldReport_list') {
                  controlCenter.push(childrenItem)
                }
                //首页按钮权限
                if (childrenItem.name == 'equipment_list' || childrenItem.name == 'data_historyForm' || childrenItem.name == 'alarmRecord_list' || childrenItem.name == 'passport_list'){
                  homeBtn.push(childrenItem)
                }
                roles.permissionList.push(childrenItem.name)
              })
            }
          });
          let home = {
            children: homeBtn,
            show_name: "首页",
            name: "home",
          }
          roles.permissionList.push("home")
          roles.permission.push(home)
          roles.permission.forEach(item=>{
            // item.home
             //添加定时任务添加权限去控制中心里面
            if (item.name == "controlCenter") {
              item.children.push(...controlCenter)
            }
             //添加设备列表添加权限去用户中心里面
            if (item.name == "userManagement") {
              item.children.push(equipmentList)
            }
          })
          // console.log(roles);
          store.dispatch('GenerateRoutes', { roles }).then(() => {
            // 根据roles权限生成可访问的路由表
            // 动态添加可访问路由表
            const redirect = decodeURIComponent(from.query.redirect);
            if (to.path !== redirect && redirect !== 'undefined') {
              // 跳转到目的路由
              next({ path: redirect }); 
            }
            next();
          })
        }
      } else {
        showError("获取用户权限出错，请重新登录！")
        Vue.ls.remove(ACCESS_TOKEN);
        next({ path: '/passport/login' });
        NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
      }
    })
  } else {
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next();
    } else {
      // , query: { redirect: to.fullPath }
      next({ path: '/passport/login' });
      NProgress.done(); // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
});

router.afterEach(() => {
  NProgress.done(); // finish progress bar
});
